package consulTest.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.function.BiConsumer;

@Slf4j
@Component
public class MLoggingFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws IOException {
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(httpServletRequest);
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(httpServletResponse);
        BiConsumer<ContentCachingRequestWrapper, ContentCachingResponseWrapper> consumer =
                (ContentCachingRequestWrapper a, ContentCachingResponseWrapper b) -> {
                    try {
                        filterChain.doFilter(requestWrapper, responseWrapper);
                    } catch (IOException | ServletException e) {
                        logger.error("==>", e);
                    }
                };

        HTTPLogUtil.log(requestWrapper, responseWrapper, consumer);
        responseWrapper.copyBodyToResponse();
    }
}
